package com.banciyuan.bcywebview.biz.main.newdiscover.tuijian;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.DiscoverApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DiscoverChoiceItem;

/**
 * Created by squall on 2017/7/17.
 */

public class TuijianFragment extends BaseLazyContainerFragment {

    private PullToRefreashRecycleView pullToRefreashRecycleView;
    private RecyclerView mRecyclerView;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    private RequestQueue mQueue;
    private List<DiscoverChoiceItem> dlist = new ArrayList<>();
    private TuijianAdapter tuijianAdapter;

    private int page = 1;
    private boolean is_load;
    private boolean is_end;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.discover_layout, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();

        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initUi(View rootView) {
        pullToRefreashRecycleView = (PullToRefreashRecycleView) rootView.findViewById(R.id.timeline_refresh_lv);
        mRecyclerView = pullToRefreashRecycleView.getRefreshableView();
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? 2 : 1;
            }
        });
        mRecyclerView.setLayoutManager(layoutManager);
        tuijianAdapter = new TuijianAdapter(dlist, getActivity());
        mRecyclerView.addItemDecoration(new TuijianDecoration(getActivity()));
        mRecyclerView.setAdapter(tuijianAdapter);
    }

    @Override
    protected void initAction() {
        mRecyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!is_load && !is_end) {
                    page++;
                    initData();
                }
            }
        });

        pullToRefreashRecycleView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                page = 1;
                is_end = false;
                is_load = false;
                initData();
            }
        });
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootView) {
        mProgressbarView = rootView.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initData() {
        is_load = true;
        String url = HttpUtils.BASE_URL + DiscoverApi.getIndexdata();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    JSONObject jsonObject = new JSONObject(response);
                    List<DiscoverChoiceItem> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<DiscoverChoiceItem>>() {
                    }.getType());
                    renderData(popIllegalDiscoverData(templist));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private List<DiscoverChoiceItem> popIllegalDiscoverData(List<DiscoverChoiceItem> data) {
        List<DiscoverChoiceItem> choiceItemList = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            if ("coser".equals(data.get(i).getType()) || "illust".equals(data.get(i).getType())
                    || "group".equals(data.get(i).getType()) || "group_post".equals(data.get(i).getType())
                    || "daily".equals(data.get(i).getType()) || "novel".equals(data.get(i).getType())
                    || "zhipin_goods".equals(data.get(i).getType())) {
                choiceItemList.add(data.get(i));
            }
        }
        return choiceItemList;
    }

    private void renderData(List<DiscoverChoiceItem> data) {
        if (data.isEmpty()) is_end = true;
        if (page == 1) {
            dlist.clear();
        }
        int start = dlist.size();
        dlist.addAll(data);
        if (tuijianAdapter != null) {
            if (page == 1) {
                tuijianAdapter.notifyDataSetChanged();
            } else {
                tuijianAdapter.notifyItemRangeInserted(start + 1, data.size());
            }
        } else {
            tuijianAdapter = new TuijianAdapter(dlist, getActivity());
            mRecyclerView.setAdapter(tuijianAdapter);
        }
        is_load = false;
        mProgressbarHelper.onSuccess();
        pullToRefreashRecycleView.onRefreshComplete();
    }
}
